<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';
import consola from 'consola';

import { DefGenTableApi } from '#/api/devOperation/developer/defGenTable';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { createCrudOptions } from '../data/importCrud';

interface Emits {
  (e: 'success'): void;
}
defineOptions({
  name: '表结构导入',
  inheritAttrs: false,
});
const emit = defineEmits<Emits>();
const { crudRef, crudBinding, crudExpose, selectedRowKeys } = useFs({
  createCrudOptions,
});
const { createConfirm, createMessage } = useMessage();

const onOpened = async () => {
  modalApi.setState({ loading: false, confirmLoading: false });

  const searchRef = crudExpose.getSearchRef();
  searchRef.getComponentRef('dsId').reloadDict();
};

async function onConfirm() {
  const tableNames = selectedRowKeys.value;
  if (!tableNames || tableNames.length <= 0) {
    createMessage.warning($t('common.tips.pleaseSelectTheData'));
    return;
  }
  const model = crudExpose.getSearchFormData();
  const dsId = model.dsId;
  if (!dsId) {
    createMessage.warning('请先选择数据源');
    return;
  }
  try {
    const flag = await DefGenTableApi.importCheck(tableNames);
    if (flag) {
      await DefGenTableApi.importTable({ dsId, tableNames });
      modalApi.close();
      selectedRowKeys.value = [];
      emit('success');
    }
  } catch (error: any) {
    if (error?.msg?.indexOf('是否继续导入') > -1) {
      const msg = error?.msg ?? '是否确认导入此表？';
      createConfirm({
        iconType: 'warning',
        title: () => '提示',
        content: msg,
        onOk: async () => {
          try {
            await DefGenTableApi.importTable({ dsId, tableNames });
            modalApi.close();
            selectedRowKeys.value = [];
            emit('success');
          } catch (error: any) {
            consola.log('warn', error);
          }
        },
      });
    }
  }
}

const [Modal, modalApi] = useVbenModal({
  onOpened,
  onConfirm,
});

defineExpose(modalApi);
</script>

<template>
  <Modal class="h-[100%] w-[100%]" title="导入表结构">
    <FsPage>
      <FsCrud ref="crudRef" v-bind="crudBinding" />
    </FsPage>
  </Modal>
</template>
